<?php
/**
 * Created by PhpStorm.
 * User: Ysll <754060604@qq.com>
 * Date: 2017/9/12
 * Time: 10:28
 */

function getAllFriendlyLink()
{
    $db = require 'DatabaseService.php';
    $result = mysqli_query($db, 'SELECT * FROM `friendly_link`;');
    return mysqli_fetch_all($result, MYSQLI_ASSOC);
}


function findLinkById($id) {
    $db = require 'DatabaseService.php';
    $result = mysqli_query($db, 'SELECT * FROM `friendly_link` WHERE id = ' . $id);
    return mysqli_fetch_assoc($result);
}

/**
 * @param $data
 * @return int
 */
function createFriendlyLink($data)
{
    $db = require 'DatabaseService.php';
    $key = '';
    $value = '';
    foreach ($data as $k => $v) {
        $key .= "`$k`,";
        $value .= "'$v',";
    }
    $value = rtrim($value, ',');
    $key = rtrim($key, ',');
    $sql = "INSERT INTO friendly_link ({$key}) VALUES ({$value})";
    $result = mysqli_query($db, $sql);
    if ($result == false || mysqli_errno($db)) {
        $_SESSION['error_code'] = 30000;
        $_SESSION['error_data'] = mysqli_error($db);
        return 0;
    }
    return mysqli_insert_id($db);
}

function deleteLink($id) {
    $db = require 'DatabaseService.php';
    $sql = "DELETE FROM friendly_link WHERE id = {$id}";
    $result = mysqli_query($db, $sql);
    if ($result == false || mysqli_errno($db)) {
        $_SESSION['error_code'] = 30000;
        $_SESSION['error_data'] = mysqli_error($db);
        return 0;
    }
    return 1;
}

function updateLink($id, $data)
{
    $db = require 'DatabaseService.php';
    $params = '';
    foreach ($data as $k => $v) {
        $params .= "`{$k}` = '{$v}',";
    }
    $params = rtrim($params, ',');
    $sql = "UPDATE friendly_link SET $params WHERE id = $id";
    $result = mysqli_query($db, $sql);
    if ($result == false || mysqli_errno($db)) {
        $_SESSION['error_code'] = 30000;
        $_SESSION['error_data'] = mysqli_error($db);
        return 0;
    }
    return 1;
}

function showFriendlyLink() {
    $links = getAllFriendlyLink();
    echo "<div style='font-size: 0'>";
    foreach ($links as $link) {
        echo "<p style='width: 33%;display: inline-block'><a target='_blank' style='font-size: 15px' href='{$link['link']}'>{$link['title']}</a></p>";
    }
    echo "<div>";
}